package com.cloud.custom.workflow.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.cloud.custom.common.exception.BizException;
import com.cloud.custom.common.result.QkIcon;
import com.cloud.custom.common.result.QkTreeNode;
import com.cloud.custom.common.utils.SessionHelper;
import com.cloud.custom.interfaces.FeignClientFreeflow;
import com.cloud.custom.interfaces.FeignClientSystem;
import com.cloud.custom.workflow.bean.WfActDef;
import com.cloud.custom.workflow.bean.WfActPart;
import com.cloud.custom.workflow.entity.WfActChoice;
import com.cloud.custom.workflow.entity.WfActInst;
import com.cloud.custom.workflow.entity.WfTransInst;
import com.cloud.custom.workflow.enums.WfItemTypeEnum;
import com.cloud.custom.workflow.enums.WfPartEnum;
import com.cloud.custom.workflow.mapper.WfActChoiceMapper;
import com.cloud.custom.workflow.mapper.WfActInstMapper;
import com.cloud.custom.workflow.mapper.WfTransInstMapper;
import com.cloud.custom.workflow.service.WorkflowSearchService;

import tk.mybatis.mapper.entity.Example;

@Service
public class WorkflowSearchServiceImpl implements WorkflowSearchService {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private WfActInstMapper wfActInstMapper;

	@Autowired
	private WfActChoiceMapper wfActChoiseMapper;

	@Autowired
	private WfTransInstMapper wfTransInstMapper;

	@Autowired
	private FeignClientFreeflow feignClientFreeFlow;

	@Autowired
	private FeignClientSystem feignClientSystem;

	@Override
	public QkTreeNode[] searchTransitTreeNodes(long recId, long actId) {
		WfActInst inst = wfActInstMapper.selectByPrimaryKey(actId);
		// 1.获取当前环节节点可以抵达的下一个节点相关属性，以及节点上的参与者
		List<WfActDef> nextActs = feignClientFreeFlow.searchNextActDefs(inst.getActDefId());
		List<WfActDef> enableAct = new ArrayList<WfActDef>();
		// 2.流向过滤
		for (WfActDef actDef : nextActs) {
			if (!StringUtils.isEmpty(actDef.getTransFilterSql())) {
				try {
					int i = jdbcTemplate.queryForObject(actDef.getTransFilterSql(), Integer.class);
					if (i > 0) {
						enableAct.add(actDef);
					}
				} catch (Exception e) {
					throw new BizException(500, actDef.getActDefName() + " 节点流向上的过滤SQL语法错误");
				}
			} else {
				enableAct.add(actDef);
			}
		}
		List<QkTreeNode> results = new ArrayList<QkTreeNode>();
		// 3.参与者过滤、岗位细化到人
		for (WfActDef actDef : nextActs) {
			List<WfActPart> parts = actDef.getParts();
			List<QkTreeNode> partNodes = new ArrayList<QkTreeNode>();
			for (WfActPart p : parts) {
				if (!StringUtils.isEmpty(p.getPartFilterSql())) {
					try {
						int i = jdbcTemplate.queryForObject(actDef.getTransFilterSql(), Integer.class);
						if (i <= 0) {
							continue;
						}
					} catch (Exception e) {
						throw new BizException(500, actDef.getActDefName() + " 节点流向上的过滤SQL语法错误");
					}
				}
				// 检查是否为岗位或机构，是否需要细化到人
				if (!WfPartEnum.HUMAN.getPartType().equals(p.getPartType()) && (actDef.getActDefAttrId() & 8) == 8) {
					List<WfActPart> wps = feignClientSystem.searchTransitHumanInfo(p.getPartType(), p.getPartId(),
							SessionHelper.get().getUnitId(), (actDef.getActDefAttrId() & 8) == 8);
					//岗位机构节点
					QkTreeNode seniorNode = new QkTreeNode(p.getPartType() + "_" + p.getPartId(), p.getPartName());
					seniorNode.setSelectable(false);
					seniorNode.setLeaf(false);
					seniorNode.setExpanded(true);
					seniorNode.setExpandedIcon(QkIcon.FA_FOLDER_OPEN);
					seniorNode.setCollapsedIcon(QkIcon.FA_FOLDER);
					seniorNode.setSeniorId("ACT_" + actDef.getActDefId());
					partNodes.add(seniorNode);
					if (null != wps && wps.size() > 0) {
						for (WfActPart wp : wps) {
							// 创建节点，放入List
							QkTreeNode node = new QkTreeNode(wp.getPartType() + "_" + wp.getPartId(), wp.getPartName());
							node.setLeaf(true);
							node.setIcon(QkIcon.FA_USER);
							node.setSelectable(true);
							node.setSeniorId(p.getPartType() + "_" + p.getPartId());
							Map<String, Object> data = new HashMap<String, Object>();
							data.put("act_def_id", actDef.getActDefId());
							data.put("act_def_name", actDef.getActDefName());
							data.put("trans_def_id", actDef.getTransDefId());
							data.put("part_id", wp.getPartId());
							node.setData(data);
							partNodes.add(node);
						}
					}
				} else {
					// 创建节点，放入List
					QkTreeNode node = new QkTreeNode(p.getPartType() + "_" + p.getPartId(), p.getPartName());
					node.setLeaf(true);
					if (WfPartEnum.HUMAN.getPartType().equals(p.getPartType())) {
						node.setIcon(QkIcon.FA_USER);
					} else if (WfPartEnum.ROLE.getPartType().equals(p.getPartType())) {
						node.setIcon(QkIcon.FA_REGISTERED);
					} else if (WfPartEnum.UNIT.getPartType().endsWith(p.getPartType())) {
						node.setIcon(QkIcon.FA_UNIVERSITY);
					}
					node.setSelectable(true);
					node.setSeniorId("ACT_" + actDef.getActDefId());
					Map<String, Object> data = new HashMap<String, Object>();
					data.put("act_def_id", actDef.getActDefId());
					data.put("act_def_name", actDef.getActDefName());
					data.put("part_id", p.getPartId());
					data.put("trans_def_id", actDef.getTransDefId());
					node.setData(data);
					partNodes.add(node);
				}
			}

			if (partNodes.size() > 0) {
				QkTreeNode node = new QkTreeNode("ACT_" + actDef.getActDefId(), actDef.getActDefName());
				node.setRootFlag(true);
				node.setLeaf(false);
				node.setExpanded(true);
				node.setIcon(QkIcon.FA_TV);
				node.setSelectable(false);
				partNodes.add(node);
			}
			results.addAll(partNodes);
		}
		return results.toArray(new QkTreeNode[results.size()]);
	}

	@Override
	public List<WfActChoice> listActTransChoise(long actId) {
		WfActInst inst = wfActInstMapper.selectByPrimaryKey(actId);
		Example example = new Example(WfActChoice.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("humanId", SessionHelper.get().getHumanId());
		criteria.andEqualTo("actDefId", inst.getActDefId());
		example.orderBy("frequency").desc();
		return wfActChoiseMapper.selectByExample(example);
	}

	@Override
	public WfTransInst showRollback(long recId, long actId) {
		WfActInst inst = wfActInstMapper.selectByPrimaryKey(actId);
		Example example = new Example(WfTransInst.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("itemTypeId", WfItemTypeEnum.TRANSIT.getItemTypeId());// 批转
		criteria.andEqualTo("toActDefId", inst.getActDefId());
		criteria.andEqualTo("recId", recId);
		example.orderBy("transId").desc();
		List<WfTransInst> trans = wfTransInstMapper.selectByExample(example);
		if (trans != null && trans.size() > 0) {
			return trans.get(0);
		}
		return null;
	}

}
